package com.hinnotek.amoeba.api

import com.xuexiang.xupdate.proxy.IUpdateHttpService
import com.xuexiang.xutil.net.JsonUtil
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.FileCallBack
import com.zhy.http.okhttp.callback.StringCallback
import com.zhy.http.okhttp.request.RequestCall
import okhttp3.Call
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Request
import java.io.File

class OKHttpUpdateHttpService  : IUpdateHttpService {


    override  fun asyncGet(
        url: String,
        params: MutableMap<String, Any>,
        callBack: IUpdateHttpService.Callback
    ) {
        OkHttpUtils.get()
            .url(url)
            .build()
            .execute(object : StringCallback() {
                override fun onError(call: Call, e: java.lang.Exception, id: Int) {
                    callBack.onError(e)
                }

                override fun onResponse(response: String, id: Int) {
                    callBack.onSuccess(response)
                }
            })

    }

    override fun asyncPost(
        url: String,
        params: MutableMap<String, Any>,
        callBack: IUpdateHttpService.Callback
    ) {

        //这里默认post的是Form格式，使用json格式的请修改 post -> postString
        val requestCall: RequestCall = OkHttpUtils.postString()
            .url(url)
            .content(JsonUtil.toJson(params))
            .mediaType("application/json; charset=utf-8".toMediaTypeOrNull())
            .build()
        requestCall
            .execute(object : StringCallback() {
                override fun onResponse(response: String, id: Int) {
                    callBack.onSuccess(response)
                }
                override fun onError(call: Call, e: java.lang.Exception, id: Int) {
                    callBack.onError(e)
                }
            })
    }

    override fun download(
        url: String,
        path: String,
        fileName: String,
        callback: IUpdateHttpService.DownloadCallback
    ) {
        OkHttpUtils.get()
            .url(url)
            .tag(url)
            .build()
            .execute(object : FileCallBack(path, fileName) {
                override fun inProgress(progress: Float, total: Long, id: Int) {
                    callback.onProgress(progress, total)
                }

                override fun onError(call: Call, e: Exception, id: Int) {
                    callback.onError(e)
                }

                override fun onResponse(response: File, id: Int) {
                    callback.onSuccess(response)
                }

                override fun onBefore(request: Request, id: Int) {
                    super.onBefore(request, id)
                    callback.onStart()
                }
            })
    }

    override fun cancelDownload(url: String) {

    }
}